import { useEffect, useState, useRef } from 'react';
import { viewUtils } from '@/utils/arcgis/index';
import { jsapi, geometryUtils } from '@/utils/arcgis';

/**
 * home hook - 地图home逻辑抽成hook
 *
 * @returns [isLoading, reset] - 罗盘加载状态，和重置地图方向函数
 * @author leway
 * @date 2020-07-16
 * @beta
 */
function useHome(initialExtent?: any): [boolean, () => void] {
  const [isLoading, setIsLoading] = useState(true);
  const vmRef = useRef<any>();

  useEffect(() => {
    init();
  }, []);

  async function init() {
    const view = await viewUtils.isViewReady();
    const [HomeViewModel] = await jsapi.load(['esri/widgets/Home/HomeViewModel']);
    setTimeout(() => {
      // 增加一个延时来确保记录下，由js进行的地图初始化位置调整
      // todo 也许需要暂时停止drag, 鼠标滚轮的事件冒泡，确保用户无法操作地图？
      vmRef.current = new HomeViewModel({ view });
      setIsLoading(false);
    }, 200);
  }

  async function reset() {
    let extent;
    if (!vmRef.current || vmRef.current.state !== 'ready') {
      return;
    }

    const view = await viewUtils.isViewReady();
    try {
      // @ts-ignore
      // extent = await geometryUtils.jsonToExtent(window.appcfg.jsapiConfig.initialExtent);
      if (!initialExtent) throw new Error('没传初始值');
      extent = await geometryUtils.jsonToExtent(initialExtent);
      console.log(extent);
    } catch (error) {
      extent = vmRef.current.viewpoint;
    }
    view.goTo(extent);
  }

  return [isLoading, reset];
}

export default useHome;
